import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/index.dart';
import 'package:yp/services/api.dart';
import 'package:yp/util/util.dart';
import 'package:yp/utils/util.dart';
import 'package:yp/widgets/button_widget.dart';
import 'package:yp/widgets/index.dart';

import '../../router.dart';

class RandomAmount extends StatefulWidget {
  const RandomAmount({Key key}) : super(key: key);

  @override
  _RandomAmountState createState() => _RandomAmountState();
}

class _RandomAmountState extends State<RandomAmount>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  bool receive = false;
  Map activity;
  Map inviteCouponMap = {};
  List results = [];
  bool showTip = false;

  @override
  void initState() {
    if (Get.arguments == null) {
      var activity_num_id = getQueryVariable('activity_num_id');
      var event_num_id = getQueryVariable('event_num_id');
      print(">>>>>>>>data = $event_num_id");
      // var url = Config.WEB_URL +
      //     'mall_login?activity_num_id=$activity_num_id&event_num_id=$event_num_id';

      // webpay(url);
      if (SpUtil.getInt('empeNumId') == 0 ||
          SpUtil.getInt('empeNumId') == null) {
        var url = Config.WEB_URL +
            'mall_login?activity_num_id=$activity_num_id&event_num_id=$event_num_id&page=random_amount';

        webpay(url);
        // Get.offAllNamed(RouteConfig.mallLogin, arguments: {
        //   'activity_num_id': activity_num_id,
        //   'event_num_id': event_num_id,
        // });
        return;
      } else {
        activity = {
          'activity_num_id': activity_num_id,
          'event_num_id': event_num_id
        };
        init();
      }
    } else {
      activity = {
        "activity_num_id": Get.arguments['activity_num_id'],
        "event_num_id": Get.arguments['event_num_id'],
      };
      init();
    }
    print('argumentsactivity');
    print(activity);

    super.initState();
    _controller = AnimationController(vsync: this);
  }

  init() {
    if (activity == null) {
      toast("参数异常");
      return;
    }
    var p = {
      'sql_id': 'SCRM-FISSION-MEMBWE-GET-SIGN',
      'input_param': {
        'activity_num_id': activity["activity_num_id"],
        'mobile_phone': SpUtil.getString('number'),
        'event_num_id': activity["event_num_id"],
      }
    };

    print("ykcloud.member.new.luck.envelope.get==$p");
    Api.commonSQL(p).listen((event) {
      if (event["code"] == 0) {
        if (event["results"][0]["get_sign"] > 0) {
          getmoney(showToast: false);

          setState(() {
            receive = true;
          });
        }
      }
    });
    // var params2 = {
    //   "usr_num_id": SpUtil.getInt('empeNumId'),
    //   'access_token': SpUtil.getString('token'),
    //   "activityids": [activity['activity_num_id']] //全规则编号(多个)
    // };
    // Api.couponclaim(params2).listen((event) {
    //   if (event['code'] == 0) {
    //     if (event['card_tickets'][0]['relation'] == 1) {
    //       setState(() {
    //         receive = true;
    //       });
    //     }
    //     // if (event['results'] != null && event['results'].length > 0) {
    //     //   setState(() {
    //     //     results = event['results'];
    //     //   });
    //     // }
    //   } else {
    //     toast(event['message']);
    //   }
    // });
  }

  getmoney({bool showToast = true}) {
    var params = {
      "activity_num_id": activity['activity_num_id'],
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      'event_num_id': activity['event_num_id'],
    };
    // print("ykcloud.member.new.luck.envelope.get==$params");
    // params = {
    //   "activity_num_id": "2112270010001",
    //   "usr_num_id": 11811,
    //   "access_token": "885493233615448bba0ecaba83ee51b1",
    //   "event_num_id": "2112270010007"
    // };
    Api.envelopeget(params).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          inviteCouponMap = event;
          receive = true;
        });
        print(inviteCouponMap);
        if (showToast) {
          toast('恭喜，领券成功');
        }
        var params = {
          "sql_id": "SCRM_ MEMBER_FISSION_COUPON_QUERY_BY_USER",
          "input_param": {
            "activity_num_id": activity['activity_num_id'],
            "usr_num_id": SpUtil.getInt('empeNumId'),
            'event_num_id': activity['event_num_id'],
            'access_token': SpUtil.getString('token'),
          },
          "page_num": 1,
          "page_size": 10
        };

        Api.workCexport(params).listen((event) {
          if (event['code'] == 0) {
            if (event['results'] != null && event['results'].length > 0) {
              setState(() {
                results = event['results'];
              });
            }
          } else {}
        });
      } else {
        toast(event['message']);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  TextEditingController _phoneTextController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Scaffold(
          appBar: YPNavigationBar(
            '拼手气红包',
            onPressed: () {
              Get.offAllNamed(RouteConfig.main);
            },
            canBack: false,
          ),
          // floatingActionButton: GestureDetector(
          //   onTap: () {
          //     Get.offAllNamed(RouteConfig.main);
          //   },
          //   child: Container(
          //     width: 50,
          //     height: 50,
          //     decoration: BoxDecoration(
          //       color: Color(0xfff84034),
          //       borderRadius: BorderRadius.circular(25),
          //     ),
          //     child: Icon(Icons.home, color: Colors.white),
          //   ),
          // ),
          body: SingleChildScrollView(
              child: Column(
            children: [
              Image.asset(
                'assets/images/shouqibg.jpg',
                width: double.infinity,
              ),
              // Placeholder(fallbackHeight: 270),
              _phone(),
              _rule(),
              SizedBox(
                height: 20,
              )
            ],
          )),
          backgroundColor: Color(0xffffa9af),
        ),
        // if (showTip)
        //   Container(
        //     color: Colors.black45.withOpacity(.75),
        //     child: Center(
        //         child: Text(
        //       "请点击右上角的'...'\n然后选择在浏览器打开",
        //       style: TextStyle(
        //         color: Colors.white,
        //         fontSize: 18,
        //       ),
        //       textAlign: TextAlign.center,
        //     )),
        //   ),
      ],
    );
  }

  Widget _phone() {
    return Container(
      decoration: BoxDecoration(
          color: EsColors.White,
          borderRadius: BorderRadius.all(Radius.circular(5))),
      padding: EdgeInsets.fromLTRB(12, 30, 12, 0),
      margin: EdgeInsets.all(12),
      child: Column(
        children: [
          Column(
            children: [
              Offstage(
                offstage: !receive,
                child: Container(
                  width: double.infinity,
                  height: 200.w,
                  margin: EdgeInsets.only(top: 36.w, bottom: 20.w),
                  child: Row(children: [
                    Expanded(
                      flex: 1,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          RichText(
                              maxLines: 1,
                              textAlign: TextAlign.center,
                              text: TextSpan(children: [
                                TextSpan(
                                    text: '￥',
                                    style: TextStyle(
                                        fontSize: EsSizes.LG * 2.sp,
                                        fontWeight: EsFontWeights.SemiBold,
                                        color: EsColors.White)),
                                TextSpan(
                                    text: inviteCouponMap['face_value']
                                        .toString(),
                                    style: TextStyle(
                                        fontSize: 40 * 2.sp,
                                        fontWeight: EsFontWeights.SemiBold,
                                        color: EsColors.White))
                              ])),
                          Container(
                            padding: EdgeInsets.symmetric(
                                vertical: 0, horizontal: 20.w),
                            decoration: BoxDecoration(
                                color: Color(0xffd32f14),
                                borderRadius: BorderRadius.circular(16.w)),
                            child: Text(
                              inviteCouponMap['least_cost'] == null
                                  ? "无门槛"
                                  : "满${inviteCouponMap['least_cost'].toString().replaceAll('.0', '')}元可用",
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  color: EsColors.White,
                                  fontSize: EsSizes.XS * 2.sp,
                                  fontWeight: EsFontWeights.Normal),
                            ),
                          )
                        ],
                      ),
                    ),
                    Expanded(
                        flex: 2,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              inviteCouponMap['title'] != null
                                  ? inviteCouponMap['title']
                                  : '',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  color: EsColors.MoneySecondary,
                                  fontSize: EsSizes.MD * 2.sp,
                                  fontWeight: EsFontWeights.SemiBold),
                            ),
                            SizedBox(height: 14),
                            Text(
                              "APP、小程序专享",
                              style: TextStyle(
                                  color: Color(0XFFA64F00),
                                  fontSize: EsSizes.XS * 2.sp,
                                  fontWeight: EsFontWeights.Normal),
                            ),
                          ],
                        ))
                  ]),
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          fit: BoxFit.fill,
                          image:
                              AssetImage('assets/images/give_coupons_bg.png'))),
                ),
              ),
              // Placeholder(fallbackHeight: 100),
              SizedBox(height: 20),
              if (receive)
                Text(
                  '优惠券已发放至：${SpUtil.getString('usr_phone_num')}',
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: EsColors.Title,
                      fontSize: EsSizes.MD,
                      fontWeight: EsFontWeights.Medium),
                ),
            ],
          ),
          // Visibility(
          //   visible: !_receive,
          //   child: TextField(
          //     decoration: InputDecoration(hintText: '请输入手机号领取优惠'),
          //     controller: _phoneTextController,
          //     keyboardType: TextInputType.phone,
          //     onChanged: (info) {
          //       setState(() {});
          //     },
          //   ),
          // ),
          SizedBox(height: 27),
          EsOutLineButton(
            receive == false ? '立即领取' : '请下载APP后使用',
            fontSize: EsSizes.LG,
            textColor: EsColors.White,
            bgColor: Color(0xfff84034),
            borderColor: Colors.transparent,
            borderRadius: 28,
            padding: EdgeInsets.symmetric(horizontal: 100, vertical: 20),
            onTap: () {
              print('立即领取');
              if (receive == false) {
                getmoney();
              } else {
                if (!kIsWeb) {
                  Get.offAllNamed(RouteConfig.main);
                  return;
                }
                // toast("请下载app使用");
                webpay("${Config.WEB_DOWN_URL}download.html");
                // Future.delayed(Duration(seconds: 1), () {
                //   if (isWechat()) {
                //     // toast('请在系统浏览器打开本页面');
                //     setState(() {
                //       showTip = true;
                //     });
                //   } else {
                //     /// 进入下载页
                //     toast("请下载app使用");
                //     webpay("${Config.WEB_DOWN_URL}download.html");
                //   }
                // });
                // webpay(
                //     "yinpinhui://zrhsh.com/app?random_amount=1&activity_num_id=${getQueryVariable('activity_num_id')}&event_num_id=${getQueryVariable('event_num_id')}");
              }

              // if (_phoneTextController.text.isNotEmpty) {

              // }
            },
          ),
          SizedBox(height: 20),
          Visibility(
            visible: receive,
            child: Row(
              children: [
                Expanded(
                    child: Container(color: EsColors.BackGround, height: 1)),
                SizedBox(width: 12),
                Text(
                  '看看朋友手气如何',
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: EsColors.Content,
                      fontSize: EsSizes.LG,
                      fontWeight: EsFontWeights.Normal),
                ),
                SizedBox(width: 12),
                Expanded(
                    child: Container(color: EsColors.BackGround, height: 1))
              ],
            ),
          ),
          SizedBox(height: receive ? 0 : 30),
          results.length > 0 ? _friend() : Container()
        ],
      ),
    );
  }

  Widget _friend() {
    return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: results.length,
        itemBuilder: (contxte, index) {
          return Padding(
            padding: EdgeInsets.only(top: 20),
            child: Row(
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      results[index]['mobile_phone']
                          .toString()
                          .replaceFirst(new RegExp(r'\d{4}'), '****', 3)
                          .toString(),
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: EsColors.Title,
                          fontSize: EsSizes.LG,
                          fontWeight: EsFontWeights.Medium),
                    ),
                    SizedBox(height: 8),
                    Text(
                      results[index]['create_dtme'].toString(),
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: EsColors.Content,
                          fontSize: EsSizes.SM,
                          fontWeight: EsFontWeights.Normal),
                    )
                  ],
                ),
                Expanded(
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: Text(
                      results[index]['face_value'].toString() + '元',
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: EsColors.Money,
                          fontSize: EsSizes.XL,
                          fontWeight: EsFontWeights.SemiBold),
                    ),
                  ),
                ),
              ],
            ),
          );
        });
  }

  Widget _rule() {
    return Container(
      decoration: BoxDecoration(
          color: EsColors.White,
          borderRadius: BorderRadius.all(Radius.circular(5))),
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 30),
      margin: EdgeInsets.fromLTRB(12, 0, 12, 12),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(child: Container(color: EsColors.BackGround, height: 1)),
              SizedBox(width: 12),
              Text(
                '红包规则',
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: EsColors.Content,
                    fontSize: EsSizes.LG,
                    fontWeight: EsFontWeights.Normal),
              ),
              SizedBox(width: 12),
              Expanded(child: Container(color: EsColors.BackGround, height: 1))
            ],
          ),
          SizedBox(height: 14),
          Text(
            '1、红包默认会发送到您的账户，进入微信小程序或app可以使用。 \n2、每个订单仅限使用一张优惠券。 \n3、活动最终解释权归合作商户所有。',
            style: TextStyle(
                color: EsColors.Content,
                fontSize: EsSizes.XS,
                fontWeight: EsFontWeights.Normal),
          ),
          SizedBox(height: 14)
        ],
      ),
    );
  }
}
